import React from "react";
import { Tabs, Space, Input, DatePicker } from "antd";
import TheButton from "@/components/TheButton";
import TheTable from "@/components/TheTable";
import ThePagination from "@/components/ThePagination";
import "@/views/commodity/style/style.less";
import { apiGetReturnOrderDetails, apiOrderRefundSubmit } from '@/request/orderManagement'
import { getDateTime3 } from '@/utils/getDate'
import { exportSheetTable } from '@/utils/exportTable.js'

const { RangePicker } = DatePicker;
const { Search } = Input;
const { TabPane } = Tabs;

class Chargeback extends React.Component {
  state = {
    salesReturnStatus: '1',
    columns1: [
      {
        title: "退单编号",
        dataIndex: "returnCode",
        key: "returnCode",
      },
      {
        title: "订单编号",
        dataIndex: "orderCode",
        key: "orderCode",
      },
      {
        title: "用户昵称",
        dataIndex: "orderMemberName",
        key: "orderMemberName",
      },
      {
        title: "所属门店",
        dataIndex: "orderTypeName",
        key: "orderTypeName",
      },
      {
        title: "订单金额（元）",
        dataIndex: "orderTotalPrice",
        key: "orderTotalPrice",
        render: (text, render) => {
          return <React.$Price price={render.orderTotalPrice} />
        }
      },
      {
        title: "实付金额（元）",
        dataIndex: "orderPayPrice",
        key: "orderPayPrice",
        render: (text, render) => {
          return <React.$Price price={render.orderPayPrice} />
        }
      },
      {
        title: "退款金额",
        dataIndex: "orderPayPrice",
        key: "orderPayPrice",
        render: (text, render) => {
          return <React.$Price price={render.orderPayPrice} />
        }
      },
      {
        title: "退单时间",
        dataIndex: "salesGoTime",
        key: "salesGoTime",
      },
      {
        title: "退单状态",
        dataIndex: "salesReturnStatus",
        key: "salesReturnStatus",
        render: (text, record) => {
          let label = ''
          switch (record.salesReturnStatus) {
            case 1:
              label = "退款中"
              break
            case 0:
              label = "退款失败"
              break
            case 9:
              label = "退款成功"
              break
            default:
              label = "未知退款状态"
          }
          return label;
        }
      },
      {
        title: "退单原因",
        dataIndex: "remark",
        key: "remark",
      },
      {
        title: "操作",
        fixed: "right",
        render: (text, render) => {
          return (
            <div>
              <TheButton          haspermi={['order:chargeback:details']} 
                onClick={() => this.props.history.push(`/order/chargebackDetails/${render.returnCode}`)}
              >
                查看订单
              </TheButton>
            </div>
          );
        },
      },
    ],
    columns0: [
      {
        title: "退单编号",
        dataIndex: "returnCode",
        key: "returnCode",
      },
      {
        title: "订单编号",
        dataIndex: "orderCode",
        key: "orderCode",
      },
      {
        title: "用户昵称",
        dataIndex: "orderMemberName",
        key: "orderMemberName",
      },
      {
        title: "所属门店",
        dataIndex: "orderTypeName",
        key: "orderTypeName",
      },
      {
        title: "订单金额（元）",
        dataIndex: "orderTotalPrice",
        key: "orderTotalPrice",
        render: (text, render) => {
          return <React.$Price price={render.orderTotalPrice} />
        }
      },
      {
        title: "实付金额（元）",
        dataIndex: "orderPayPrice",
        key: "orderPayPrice",
        render: (text, render) => {
          return <React.$Price price={render.orderPayPrice} />
        }
      },
      {
        title: "退款金额",
        dataIndex: "orderPayPrice",
        key: "orderPayPrice",
        render: (text, render) => {
          return <React.$Price price={render.orderPayPrice} />
        }
      },
      {
        title: "退单时间",
        dataIndex: "salesGoTime",
        key: "salesGoTime",
      },
      {
        title: "退单状态",
        dataIndex: "salesReturnStatus",
        key: "salesReturnStatus",
        render: (text, record) => {
          let label = ''
          switch (record.salesReturnStatus) {
            case 1:
              label = "退款中"
              break
            case 0:
              label = "退款失败"
              break
            case 9:
              label = "退款成功"
              break
            default:
              label = "未知退款状态"
          }
          return label;
        }
      },
      {
        title: "退单原因",
        dataIndex: "remark",
        key: "remark",
      },
      {
        title: "操作",
        fixed: "right",
        render: (text, render) => {
          return (
            <div>
              <TheButton  haspermi={['order:chargeback:details']} 
                onClick={() => this.props.history.push(`/order/chargebackDetails/${render.returnCode}`)}
              >
                查看订单
              </TheButton>
          
           <TheButton  haspermi={['order:chargeback:refund']}  onClick={() => this.chargebackConfirm(render.returnCode)}>退款</TheButton>
           
            </div>
          );
        },
      },
    ],
    columns9: [
      {
        title: "退单编号",
        dataIndex: "returnCode",
        key: "returnCode",
      },
      {
        title: "订单编号",
        dataIndex: "orderCode",
        key: "orderCode",
      },
      {
        title: "用户昵称",
        dataIndex: "orderMemberName",
        key: "orderMemberName",
      },
      {
        title: "所属门店",
        dataIndex: "orderTypeName",
        key: "orderTypeName",
      },
      {
        title: "订单金额（元）",
        dataIndex: "orderTotalPrice",
        key: "orderTotalPrice",
        render: (text, render) => {
          return <React.$Price price={render.orderTotalPrice} />
        }
      },
      {
        title: "实付金额（元）",
        dataIndex: "orderPayPrice",
        key: "orderPayPrice",
        render: (text, render) => {
          return <React.$Price price={render.orderPayPrice} />
        }
      },
      {
        title: "退款金额",
        dataIndex: "orderPayPrice",
        key: "orderPayPrice",
        render: (text, render) => {
          return <React.$Price price={render.orderPayPrice} />
        }
      },
      {
        title: "退单时间",
        dataIndex: "salesGoTime",
        key: "salesGoTime",
      },
      {
        title: "退单状态",
        dataIndex: "salesReturnStatus",
        key: "salesReturnStatus",
        render: (text, record) => {
          let label = ''
          switch (record.salesReturnStatus) {
            case 1:
              label = "退款中"
              break
            case 0:
              label = "退款失败"
              break
            case 9:
              label = "退款成功"
              break
            default:
              label = "未知退款状态"
          }
          return label;
        }
      },
      {
        title: "退单原因",
        dataIndex: "remark",
        key: "remark",
      },
      {
        title: "操作",
        fixed: "right",
        render: (text, render) => {
          return (
            <div>
              <TheButton  haspermi={['order:chargeback:details']} 
                onClick={() => this.props.history.push(`/order/chargebackDetails/${render.returnCode}`)}
              >
                查看订单
              </TheButton>
            </div>
          );
        },
      },
    ],
    dataSource1: [],
    dataSource0: [],
    dataSource9: [],
    pageData1: {
      pageNo: 1,
      pageSize: 10,
    },
    pageData0: {
      pageNo: 1,
      pageSize: 10,
    },
    pageData9: {
      pageNo: 1,
      pageSize: 10,
    },
    total1: 0,
    total0: 0,
    total9: 0,
    tabData: [
      {
        label: '退款中',
        value: '1'
      },
      {
        label: '退款成功',
        value: '9'
      },
      {
        label: '退款失败',
        value: '0'
      },
    ],
    searchValue: {
      orderMemberName: '',
      orderTypeName: '',
      orderCode: '',
      returnCode: '',
      createTimeStart: '',
      createTimeEnd: ''
    }
  };
  async componentDidMount() {
    await this.getData()
  }
  getData = async () => {
    this.setState({ loading: true })
    const { salesReturnStatus, searchValue } = this.state
    let res = await apiGetReturnOrderDetails({
      salesReturnStatus,
      ...searchValue,
      ...this.state[`pageData${salesReturnStatus}`]
    })
    if (res.data && res.code === 0) {
      this.setState({
        [`pageData${salesReturnStatus}`]: {
          pageNo: res.pageNo,
          pageSize: res.pageSize
        },
        [`dataSource${salesReturnStatus}`]: res.data,
        [`total${salesReturnStatus}`]: res.totalCount,
        loading: false
      })
    } else {
      this.setState({ loading: false })
    }
  }
  setTabKey = (salesReturnStatus) => {
    this.setState({ salesReturnStatus }, () => {
      this.getData()
    })
  };
  pageChange = (pageNo, pageSize, index) => {
    this.setState({
      [`pageData${index}`]: {
        pageNo,
        pageSize,
      },
    }, () => this.getData());
  }
  dialogCancel = () => {
    this.setState({ visible: false });
  };
  chargebackConfirm = (orderId) => {
    React.$confirm({
      title: "您确认对此订单进行退款操作吗？",
      onOk: async () => {
        this.setState({ loading: true })
        let res = await apiOrderRefundSubmit({ returnCode:orderId })
        if (res.code === 0) {
          React.$message({
            type: 'info',
            content: '退款成功'
          })
          this.getData()
        }
      },
    });
  };
  setNickName = e => {
    this.setState({
      searchValue: {
        ...this.state.searchValue,
        memberName: e
      },
      pageData1: {
        pageNo: 1,
        pageSize: 10,
      },
      pageData0: {
        pageNo: 1,
        pageSize: 10,
      },
      pageData9: {
        pageNo: 1,
        pageSize: 10,
      },
    }, () => {
      this.getData()
    })
  }
  setStoreName = e => {
    this.setState({
      searchValue: {
        ...this.state.searchValue,
        storeName: e
      },
      pageData1: {
        pageNo: 1,
        pageSize: 10,
      },
      pageData0: {
        pageNo: 1,
        pageSize: 10,
      },
      pageData9: {
        pageNo: 1,
        pageSize: 10,
      },
    }, () => {
      this.getData()
    })
  }
  setOrderCode = e => {
    this.setState({
      searchValue: {
        ...this.state.searchValue,
        orderCode: e
      },
      pageData1: {
        pageNo: 1,
        pageSize: 10,
      },
      pageData0: {
        pageNo: 1,
        pageSize: 10,
      },
      pageData9: {
        pageNo: 1,
        pageSize: 10,
      },
    }, () => {
      this.getData()
    })
  }
  setReturnCode = e => {
    this.setState({
      searchValue: {
        ...this.state.searchValue,
        returnCode: e
      },
      pageData1: {
        pageNo: 1,
        pageSize: 10,
      },
      pageData0: {
        pageNo: 1,
        pageSize: 10,
      },
      pageData9: {
        pageNo: 1,
        pageSize: 10,
      },
    }, () => {
      this.getData()
    })
  }
  datePickerChange = e => {
    if (e) {
      this.setState({
        searchValue: {
          ...this.state.searchValue,
          createTimeStart: getDateTime3(e[0]),
          createTimeEnd: getDateTime3(e[1])
        },
        pageData1: {
          pageNo: 1,
          pageSize: 10,
        },
        pageData0: {
          pageNo: 1,
          pageSize: 10,
        },
        pageData9: {
          pageNo: 1,
          pageSize: 10,
        },
      }, () => {
        this.getData()
      })
    } else {
      this.setState({
        searchValue: {
          ...this.state.searchValue,
          createTimeStart: '',
          createTimeEnd: ''
        },
        pageData1: {
          pageNo: 1,
          pageSize: 10,
        },
        pageData0: {
          pageNo: 1,
          pageSize: 10,
        },
        pageData9: {
          pageNo: 1,
          pageSize: 10,
        },
      }, () => {
        this.getData()
      })
    }
  }

  exportAll = async () => {
    const { searchValue, salesReturnStatus } = this.state
    let res = await apiGetReturnOrderDetails({ ...searchValue, salesReturnStatus, pageNo: 1, pageSize: 100, type: "Y", })
    if (res.code === 0 && res.data) {
      console.log(res.data);
      const th_arr = [
        {
          title: '门店退单列表',
          prop: '',
          children: [
            {
              title: "退单编号",
              prop: "returnCode",
            },
            {
              title: "订单编号",
              prop: "orderCode",
            },
            {
              title: "用户昵称",
              prop: "orderMemberName",
            },
            {
              title: "所属门店",
              prop: "orderTypeName",
            },
            {
              title: "订单金额（元）",
              prop: "orderTotalPrice",
              valueType:'number'
            },
            {
              title: "实付金额（元）",
              prop: "orderPayPrice",
              valueType:'number'
            },
            {
              title: "退款金额",
              prop: "orderPayPrice",
              valueType:'number'
            },
            {
              title: "退单时间",
              prop: "salesGoTime",
            },
            {
              title: "退单状态",
              prop: "salesReturnStatus",
            },
            {
              title: "退单原因",
              prop: "remark",
            },
          ]
        },

      ]
      let tb_arr = []
      res.data.forEach(item => {
        tb_arr.push({
          returnCode: item.returnCode || '/',
          orderCode: item.orderCode || '/',
          orderMemberName: item.orderMemberName || '/',
          orderTypeName: item.orderTypeName || '/',
          orderTotalPrice: Number(item.orderTotalPrice/100).toFixed(2) || '/',
          orderPayPrice: Number(item.orderPayPrice/100).toFixed(2) || '/',
          orderPayPrice: Number(item.orderPayPrice/100).toFixed(2) || '/',
          salesGoTime: item.salesGoTime || '/',
          salesReturnStatus: item.salesReturnStatus===1?"退款中":item.salesReturnStatus===0?"退款失败":item.salesReturnStatus===9?"退款成功": '/',
          remark: item.remark || '/',
        })
      })
      exportSheetTable({ fileName: `门店退单${ salesReturnStatus ==='1'?"退款中":salesReturnStatus==='0'?"退款失败":salesReturnStatus==='9'?"退款成功":""}`, tH_data: th_arr, tB_data: tb_arr, isSheet: true, merge: false, })
    }
  }

  render() {
    const operations = {
      right: (
        <Space>
          <Search
            onSearch={(e) => this.setNickName(e)}
            style={{ width: 150 }}
            placeholder={"用户昵称"}
            allowClear
            enterButton
          />
          <Search
            onSearch={(e) => this.setStoreName(e)}
            style={{ width: 150 }}
            placeholder={"门店名称"}
            allowClear
            enterButton
          />
          <Search
            onSearch={(e) => this.setOrderCode(e)}
            style={{ width: 180 }}
            placeholder={"请输入订单号"}
            allowClear
            enterButton
          />
          <Search
            onSearch={(e) => this.setReturnCode(e)}
            style={{ width: 180 }}
            placeholder={"请输入退单号"}
            allowClear
            enterButton
          />
          <div>
            <span>下单时间 </span>
            <RangePicker onChange={(e) => this.datePickerChange(e)} />
          </div>
          <TheButton
              haspermi={['chargeback:list:export']}
              type="default"
              size="middle"
              onClick={() => this.exportAll()}
            >
              导出全部
            </TheButton>
        </Space>
      ),
    };
    const { tabData, loading } = this.state;
    return (
      <div className="p-layout-box">
        <Tabs
          onChange={(value) => this.setTabKey(value)}
          tabBarExtraContent={operations}
        >
          {tabData.map((v, i) => {
            return (
              <TabPane tab={v.label} key={v.value}>
                <div className="p-layout-content-pagination">
                  <TheTable
                    loading={loading}
                    scroll={{ x: "max-content" }}
                    columns={this.state[`columns${v.value}`]}
                    dataSource={this.state[`dataSource${v.value}`]}
                  />
                  <ThePagination
                    pageNo={this.state[`pageData${v.value}`].pageNo}
                    pageSize={this.state[`pageData${v.value}`].pageSize}
                    total={this.state[`total${v.value}`]}
                    pageChange={(pageNo, pageSize) =>
                      this.pageChange(pageNo, pageSize, v.value)
                    }
                  />
                </div>
              </TabPane>
            );
          })}
        </Tabs>
      </div>
    );
  }
}

export default Chargeback;
